<template>
  <!-- 核保点评规则组件 -->
  <div>
    <el-table :data="tableData" style="width: 100%" height="630px" ref="multipleTable" highlight-current-row border
      header-cell-class-name="table-header-class">
      <el-table-column label="项目属性" align='center' min-width="150">
        <template slot-scope="scope">
          <el-tooltip  :content="commonPropertyShowContent(scope.row.commonPropertyShow)" effect="dark" placement="top">
            <el-select v-model="scope.row.commonPropertyShow" placeholder="请选择" clearable :disabled="pageDisabled"
              @change="(val) => commonPropertyChange(val, scope.row)">
              <el-option v-for="item in commonPropertyOpts" :key="item.id" :label="item.name" :value="item.id+ ''">
              </el-option>
            </el-select>
        </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="测量结果" align='center' min-width="180">

        <template slot-scope="scope">
          <template v-if="scope.row.flag == 'standard'">
            <el-tooltip :disabled="!scope.row.measuringResult" effect="dark"
              :content="handleResult(scope.row.measuringResult)" placement="top">
              <span :class="['result-item', { 'disabled-item': pageDisabled }]"
                @click="measuringResultClick(scope.row, '测量结果')">{{ handleResult(scope.row.measuringResult) }}</span>
            </el-tooltip>
          </template>
          <template v-else-if="scope.row.flag == 'health'">
            <el-select v-model="scope.row.measuringResult" placeholder="请选择" filterable clearable>
              <el-option v-for="item in gradedFlagOpt" :key="item.id + ''" :label="item.label" :value="item.value + ''">
              </el-option>
            </el-select>
          </template>
          <template v-else>
            <span></span>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="命中标记" align='center' min-width="200">

        <template slot-scope="scope">
          <span>{{ scope.row.hitMark }}</span>
          <!-- <el-input  disabled v-model="scope.row.hitMark" ></el-input> -->
        </template>
      </el-table-column>
      <el-table-column label="操作" align='center' min-width="150" fixed="right" v-if="!pageDisabled">

        <template slot-scope="scope">
          <div style="display:flex;justify-content: center;">
            <span class="handle-btn" @click="handleAdd(scope.$index, scope.row)">新增</span>
            <span class="handle-btn" @click="handleDel(scope.$index, scope.row)">删除</span>
            <span class="handle-btn" @click="handleCopy(scope.$index, scope.row)">复制</span>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹窗 -->
    <!-- 新增疾病规则弹窗 -->
    <el-dialog v-if="conditionVisible" title="配置条件" :visible.sync="conditionVisible" width="850px"
      :close-on-click-modal="false" center>
      <conditionRelation ref="conditionRelation" :tableTitle="tableTitle" source="special" :logicDic="logicDic"
        @saveRelation="() => { conditionVisible = false }"></conditionRelation>
    </el-dialog>
  </div>
</template>

<script>
import conditionRelation from "./conditionRelation";

import constant from '@/utils/constant';
import {
  getCodeDictProjectApi
} from "@/api/medicalLibrary/examProjectLibrary";
import { getAusAsstntScorRuleInfoApi, deleteAusAsstntScorRuleInfoApi, getItemspropertiesApi } from "@/api/medicalLibrary/underwritingRule";
import { getStandardAttributesInfoApi } from "@/api/medicalLibrary/standardAttributes";
export default {
  components: {
    conditionRelation
  },
  props: {
    itemID: {
      type: Number
    },
    itemsCode: {
      type: String
    },
    itemsName: {
      type: String
    },
    logicDic: {
      type: Array,
      default: () => {
        return []
      }
    },
    pageDisabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      gradedFlagOpt: [
        {
          id: 1,
          label: '是',
          value: '1'
        },
        {
          id: 2,
          label: '否',
          value: '0'
        }
      ],
      // 字典
      commonPropertyOpts: [],  //产品类型
      conclusionDic: [], //核保结论
      conclusionRetDic: [],  //核保评点
      tableData: [{}],
      ruleGroupVersionId: '',  //版本id

      // 弹窗
      conditionVisible: false,
      tableTitle: '',  //表头名称
    }
  },
  created() {
    this.getSelectOptsList();
  },
  methods: {
    commonPropertyShowContent(commonPropertyShow){
      for(let one of this.commonPropertyOpts){
        if(one.id + '' == commonPropertyShow){
          return one.name;
        }
      }
    },
    commonPropertyChange(val, row) {
      row.measuringResult = '';
      for (let one of this.commonPropertyOpts) {
        if (one.flag == 'health' && one.id == val) {
          console.log('one',one)
          row.flag = 'health';
          break
        }else{
          row.flag = 'standard';
        }
      }
    },
    generateThreeDigitString(number) {
      // 将数字转换为字符串并获取长度
      let numberString = number.toString();
      let length = numberString.length;

      // 如果长度小于 3，用零填充到三位数
      if (length < 3) {
        numberString = '0'.repeat(3 - length) + numberString;
      }

      return numberString;
    },
    getRuleDataList(itemsCode) {
      this.$store.dispatch('loading/CHANGE_LOADING', true)
      this.tableData = []
      let params = {
        id: this.itemID,
        flag: '',
      }
      getItemspropertiesApi(params).then(res => {
        if (res.resultCode == constant.SUCCESS) {
          this.commonPropertyOpts = res.data || []
          getAusAsstntScorRuleInfoApi({ id: itemsCode }).then(res => {
            this.$store.dispatch('loading/CHANGE_LOADING', false)
            if (res.resultCode == constant.SUCCESS) {
              this.tableData = res.data || []

            }
          }).catch(err => {
            this.$store.dispatch('loading/CHANGE_LOADING', false);
          });
        }
      })

    },
    //获取产品分类、体检等级、核保结论的下拉框的数据
    getSelectOptsList() {
    },
    // 点击测量结果
    measuringResultClick(row, tableTitle) {
      if (this.pageDisabled) return
      this.tableTitle = tableTitle
      this.conditionVisible = true
      setTimeout(() => {
        // 处理配置条件列表数据
        this.$refs.conditionRelation.currentRow = row
        this.$refs.conditionRelation.handleRelation('measuringResult')
      })
    },
    // 处理测量结果的显示
    handleResult(measuringResult) {
      let result = measuringResult
      if (result) {
        result = result.replace(/\^/g, '').replace(/#/g, '').replace(/\$/g, '').replace(/\("/g, '').replace(/\"\)/g, '')
      }
      return result
    },


    /* ----列表操作按钮 */
    // 添加
    handleAdd(index, row) {
      var indexNum = this.generateThreeDigitString(this.tableData.length + 1);
      let obj = {
        commonPropertyShow: '',
        measuringResult: '',
        hitMark: this.itemsName + '-' + indexNum
      }
      this.tableData.push(obj)
      // this.tableData.splice(index+1,0,obj)
    },
    // 删除
    handleDel(_index, row) {
      this.$confirm(`是否删除此子项目信息?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.tableData.splice(_index, 1)
          if (row.id) {
            deleteAusAsstntScorRuleInfoApi({ id: row.id }).then((res) => {
              if (res.resultCode == constant.SUCCESS) {
                this.$message.success('删除成功')
              }
            })
              .catch((err) => {
              });
          } else {
            this.$message.closeAll()
            this.$message.success('删除成功')
          }
        })
        .catch(() => { })
    },
    // 复制
    handleCopy(index, row) {
      let fields = ['commonPropertyShow', 'measuringResult', 'hitMark','flag']
      let obj = {}
      fields.forEach(item => {
        if (item == "hitMark") {
          var indexNum = this.generateThreeDigitString(this.tableData.length + 1);
          obj[item] = this.itemsName + '-' + indexNum;
        } else {
          obj[item] = row[item]
        }

      })
      this.tableData.push(obj)
      // this.tableData.splice(index+1,0,obj)
    },
    // 点击子项目保存接口
    checkSaveInfo() {
      for (let one of this.tableData) {
        if (!one.commonPropertyShow) {
          this.$message.closeAll()
          this.$message.warning('项目属性不能为空!')
          return false;
        }
        if (!one.measuringResult) {
          this.$message.closeAll()
          this.$message.warning('测量结果不能为空!')
          return false;
        }
        if (!one.hitMark) {
          this.$message.closeAll()
          this.$message.warning('命中标记不能为空!')
          return false;
        }
      }
      return true;
    },
  }
}
</script>

<style lang="less" scoped>
.handle-btn {
  cursor: pointer;
  color: #409eff;
  display: inline-block;
  padding: 0 8px;
}

.result-item {
  color: #40a9fd;
  cursor: pointer;
  width: 100%;
  display: inline-block;
  height: 24px;
  line-height: 30px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.disabled-item {
  color: #606266;
  cursor: no-drop;
}

/deep/ .el-input-number__decrease,
/deep/ .el-input-number__increase {
  display: none;
}
</style>